<script setup>
import { useUserStore } from "@/store/modules/user";
import {useAppStore} from "@/store/modules/app.js";
const baseApi = ref(import.meta.env.VITE_APP_BASE_API)

import { downloadTemplate } from "@/api/common"
import { downloadFile, base64ToBlob, convertFileSize } from "@/utils/index.js";

const emits = defineEmits([
  'query',
  'update:modelValue'
])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  importOptions: {
    default: () => {
      return {
        uploadUrl: '',
        params: {
          a:1,b:2
        },
        method: '',
        downloadUrl: '',
        importParamName: 'multipartFile',
        importBtnName: '上传',
      }
    }
  },
  fileSize: {
    type: Number,
    default: 30
  },
  supportType: {
    type: Array,
    default: () => [ '.xls', '.xlsx' ]
  }
})

const visible = computed(
    {
      get(){
        return props.modelValue
      },
      set(val){
        emits('update:modelValue',val)
      }
    }
)

const userStore = useUserStore()

const appStore = useAppStore()

const show = ref(true)
const importExcelLoading = ref(false)
const downTemplateLoading = ref(false)
const errorMsg = ref({})
const uploadRef = ref(null)

const closeDialog = () => {
  uploadRef.value.clearFiles()
  show.value = true
}
const downTemplate = async () => {
  const downloadUrl = props.importOptions.downloadUrl
  const method = props.importOptions.method
  const params = props.importOptions.params
  downTemplateLoading.value = true
  const res = await downloadTemplate(downloadUrl, method, params)
  downloadFile(res)
  downTemplateLoading.value = false
}

const importExcel = () => {
  uploadRef.value.$el.querySelector('input').click()

}

/**
 * 文件上传前回调
 * @param file
 * @returns {*|boolean}
 */
const beforeUpload = (file) => {
  const fileSize = convertFileSize(file.size, 'B', 'MB',false)
  console.log(file, fileSize)
  let fileType = file.name.substring(file.name.lastIndexOf("."))
  let isExcel = props.supportType.includes(fileType)
  let isLimitSize = file.size / 1024 / 1024 < props.fileSize
  if (!isExcel) {
    ElMessage({ message: `上传附件只能为${props.supportType.join(" ")}格式，请重新选择`, type: 'error' })
  }
  if (!isLimitSize) {
    ElMessage({ message: `上传文件大小不能超过 ${this.fileSize}MB!`, type: 'error' })
  }
  let length = file.name.substring(0, file.name.lastIndexOf(".")).length
  let isLength = length <= 30
  if (!isLength) {
    ElMessage({ message: `上传文件名称长度不能超过 30个字!`, type: 'error' })
  }

  return isExcel && isLimitSize && isLength
}

/**
 * 文件上传成功回调
 * @param res
 * @param uploadFile
 * @param uploadFiles
 */
const onSuccess = (res, uploadFile, uploadFiles) => {
  if (res.code === 200){
    if (res.data && res.data.errorOutByte) {
      errorMsg.value = res.data
      show.value = false
    }else {
      emits('query')
      ElMessage({ message: '操作成功', type: 'success' })
      visible.value = false
    }
  }
}

/**
 * 文件删除回调
 * @param uploadFile
 * @param uploadFiles
 */
const onRemove = (uploadFile, uploadFiles) => {
  errorMsg.value = {}
  uploadRef.value.clearFiles()
  show.value = true
}

const downErrorResolve = () => {
  let blob = base64ToBlob(errorMsg.value.errorOutByte);
  let downloadUrl = window.URL.createObjectURL(blob);
  let anchor = document.createElement("a");
  anchor.href = downloadUrl;
  anchor.download = errorMsg.value.errorFileName;
  anchor.click();
}

const uploadRightData = () => {
  uploadRef.value.clearFiles()
  show.value = true
}

</script>

<template>
  <!--导入-->
  <v-dialog v-model="visible" title="导入" width="700px" :showBtn="false" @close="closeDialog">
    <div class="upload-wrap">
      <div class="upload">
        <el-upload
            ref="uploadRef" class="v-upload" drag
            :action="baseApi + `${importOptions.uploadUrl}`"
            :data="importOptions.params"
            :name="importOptions.importParamName"
            :headers="{ Authorization: userStore.token, 'Priority-Value': appStore.groupName }"
            v-bind="Object.assign($attrs)"
            :before-upload="beforeUpload"
            :on-success="onSuccess"
            :on-remove="onRemove"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            <div class="upload-tip">
              <p>
                文件大小不能超过{{ fileSize || 30 }}MB<span v-if="supportType.length !== 0"
              >，允许上传的文件类型：{{ supportType.join(" ") || '.xls .xlsx' }}</span
              >
              </p>
            </div>
            <div class="upload-text">
              将文件拖到此处，或<em> 点击上传 </em>
            </div>
          </div>
        </el-upload>
      </div>
      <div class="form-btn" v-if="show">
        <el-button size="small"  @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="downTemplateLoading" size="small" @click="downTemplate">
          <template #icon><i-ep-download /></template>下载导入模板</el-button>
        <el-button type="primary" :loading="importExcelLoading" size="small" @click="importExcel">
          <template #icon><i-ep-upload /></template>{{ importOptions.importBtnName }}</el-button>
      </div>
      <div class="error-box" v-if="!show">
        <div class="error-msg">
          <p>
            共分析<span class="num">{{ errorMsg.totalNum }}</span>条数据，其中
          </p>
          <p>
            正确数据<span class="num">{{ errorMsg.rightNum }}</span>条
          </p>
          <p>
            错误数据<span class="num">{{ errorMsg.errNum }}</span>条
            <span @click="downErrorResolve">下载错误分析报告文件</span>
          </p>
        </div>
        <div class="upload-btn">
          <el-button size="small" @click="visible = false">取消上传</el-button>
          <el-button type="primary" size="small" @click="uploadRightData">上传正确数据</el-button>
        </div>
      </div>
    </div>
  </v-dialog>
</template>

<style scoped lang="scss">
.upload-wrap {
  padding: 10px 50px;
  .upload {
    :deep(.v-upload) {

      .upload-tip {
        color: #999;
        font-size: 12px;
        line-height: 20px;
      }
      .upload-text {
        font-size: 16px;
        font-weight: bold;
        line-height: 35px;
        margin-bottom: 10px;
        em {
          color: #00a7ff;
          font-weight: bold;
        }
      }
    }
  }
  .error-box {
    .error-msg {
      padding-bottom: 15px;
      p {
        margin: 10px 0;
      }
      .num {
        color: red;
      }
      span {
        cursor: pointer;
        color: #00a7ff;
      }
    }
    .upload-btn {

    }
  }
}
</style>